<template>
  <!-- 询单中心的批量新建订单页面 -->
  <div class="app-container create-order">
    <div class="create-box">
      <div class="order-detail-top batch-item" style="padding-top: 8px;">
        <MediumOrderItem
          v-if="batchInfo && batchInfo.orderData"
          :data="batchInfo.orderData"
          :is-show-btn="false"
          :create-order="true"
          @createOrderBatch="toSubmit"
        />
      </div>
      <div :style="batchModel ? 'flex-direction: column' : ''" class="creat-client-oreder-box" style="width: 100%;">
        <ClientInfo ref="clientForm" :class="{'hiddent':isMediumUser }" class="batch-item"/>
        <!-- 批量新增 -->
        <div v-if="batchModel" class="batch-item" style="padding: 32px 0 64px;">
          <el-tabs v-model="activeName" closable type="border-card" @tab-click="handleClick" @tab-remove="removeTab">
            <el-tab-pane
              v-for="(item, index) in batchInfo.batchOrderInfo"
              :key="index"
              :label="`${item.name} ${item.priceType}`"
              :name="index.toString()">
              <el-form class="quote-select">
                <el-form-item label="订单信息引用">
                  <el-select
                    v-model="quoteOrderInfo"
                    popper-class="global-select-down"
                    name="quoteOrderInfo"
                    size="small"
                    @change="quoteForm">
                    <el-option
                      v-for="(item, index) in batchInfo.batchOrderInfo"
                      :key="index"
                      :label="`${item.name} ${item.priceType}`"
                      :value="index"
                      :disabled="activeName*1 === index"/>
                  </el-select>
                  <span style="display: inline-block; width: 40px;"/>
                  <span class="quote-tip">
                    <tipIcon is-diy />
                    说明：选择资源后请填写对应的订单信息并保存。没有提交订单信息的选项无法生成订单。
                  </span>
                </el-form-item>
              </el-form>
              <OrderInfo
                :ref="`orderForm${index}`"
                :class="{'isMediumUser-style':isMediumUser }"
                :style="!isMediumUser ? '':{marginTop: 0}"
                :is-disabled="isDisabled"
                :disabled-tax-amount="disabledTaxAmount"
                :seal-bill-type="sealBillType"
                :order-platform-id="orderPlatformId"
                :order-option="orderOption"
                :is-all-disabled="isMediumUser"
                :batch-write="batchWrite[index]"
                :batch-remote-request="`remoteRequestRs${index}`"
                style="margin: 0;"
                @orderFormVal="orderFormVal"/>
              <DiscountInfo
                :ref="`discountInfo${index}`"
                :batch-remote-request="`remoteRequestDc${index}`"
                style="margin: 0;"/>
              <RelatedItem
                :batch-index="index"
                :type="1"
                :ids="contractIds"
                class="related-item"
                placeholder="选择合同编号/合同名称"
                @postMessage="getRelatedContract"/>
              <el-table
                v-if="relatedContract[index] && relatedContract[index].options && relatedContract[index].options.length > 0"
                :data="relatedContract[index].options"
                style="padding: 0 32px;"
                element-loading-text="加载中..."
                empty-text="暂无数据">
                <el-table-column align="left" label="合同编号">
                  <template slot-scope="scope">
                    <span>{{ scope.row.number || '--' }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="合同有效期">
                  <template slot-scope="scope">
                    <div v-if="scope.row.validityStartTime && scope.row.validityEndTime">
                      {{ scope.row.validityStartTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} - {{ scope.row.validityEndTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}
                    </div>
                    <div v-else>--</div>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="往来单位" min-width="120">
                  <template slot-scope="scope">
                    {{ scope.row.customer || '--' }}
                  </template>
                </el-table-column>
                <el-table-column align="left" label="合同名称/项目">
                  <template slot-scope="scope">
                    <span>{{ scope.row.name || '--' }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="操作">
                  <template slot-scope="scope">
                    <span class="table-btn" @click="deleteRelated(0, scope.$index, index)">删除</span>
                  </template>
                </el-table-column>
              </el-table>
              <RelatedItem
                :batch-index="index"
                :type="2"
                :target="['id', 'no']"
                :ids="invoiceIds"
                class="related-item"
                style="margin-top: 32px;"
                placeholder="选择发票编号"
                title="关联发票"
                @postMessage="getRelatedInvoice"/>
              <el-table
                v-if="relatedInvoice[index] && relatedInvoice[index].options && relatedInvoice[index].options.length > 0"
                :data="relatedInvoice[index].options"
                style="padding: 0 32px;"
                element-loading-text="加载中..."
                empty-text="暂无数据">
                <el-table-column align="left" label="发票编号">
                  <template slot-scope="scope">
                    <span>{{ scope.row.no || '--' }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="发票号码">
                  <template slot-scope="scope">
                    <span>{{ scope.row.number || '--' }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="申请人">
                  <template slot-scope="scope">
                    <span>{{ scope.row.proposer || '--' }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="开票日期">
                  <template slot-scope="scope">
                    <span>{{ scope.row.invoiceDate || '--' }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="含税金额(元)">
                  <template slot-scope="scope">
                    <span v-if="scope.row.amountFen || scope.row.amountFen === 0" >{{ (scope.row.amountFen / 100) | moneyFilter }}</span>
                    <span v-else>--</span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="操作">
                  <template slot-scope="scope">
                    <span class="table-btn" @click="deleteRelated(1, scope.$index, index)">删除</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <!-- <div class="crm-add-btn">
        <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">保存</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
      </div> -->
    </div>
  </div>
</template>
<script>
import ClientInfo from '@/components/CreateOrder/client';
import RelatedItem from '@/components/CreateOrder/RelatedItem';
import OrderInfo from '@/components/CreateOrder/order';
import DiscountInfo from '@/components/CreateOrder/discount';
import { createOrderBatch } from '@/api/order';
import { getInfo } from '@/api/login';
import SelectOption from './mixins/selectOption';
import DataInfo from './mixins/data';
import { hasRouteAuth } from '@/utils/permission';
import MediumOrderItem from '@/components/MediumPage/order/MediumOrderListItem';
import { standardFormatNoHour } from '@/filters/date';
import { moneyFilter } from '@/filters/number';

// import { setresourceCategory } from '@/filters/status';

export default {
  components: { ClientInfo, OrderInfo, DiscountInfo, RelatedItem, MediumOrderItem },
  filters: {
    standardFormatNoHour,
    moneyFilter
  },
  mixins: [SelectOption, DataInfo],
  data() {
    return {
      title: '新增订单',
      orderId: '',
      isDisabled: false,
      disabledTaxAmount: false,
      isShow: false,
      loading: false,
      btnLoading: false,
      sealBillId: '',
      active: '',
      name: '',
      orderFormValue: '',
      sealBillType: null,
      orderPlatformId: null,
      batchModel: null, // 批量新增
      batchInfo: null, // 批量新增资源信息
      activeName: '0',
      quoteOrderInfo: null, // 当前引用的表单（index）
      relatedInvoice: [], // 关联发票
      relatedContract: [], // 关联合同
      invoiceIds: [], // 关联发票
      contractIds: [], // 关联合同
      batchWrite: [], // 回填数据
      requestFlag: true // 允许提交
    };
  },
  computed: {
    isMediumUser() {
      // 媒介用户：拥有媒介的权限但是没有，销售的权限
      /**
         * 规则：
         * 1、媒介用户仅看见订单及资源信息、成本信息
         * 2、媒介用户只可以编辑成本信息
         * 3、无法查看客信息（列表与详情页皆隐藏客户信息）
         * 4、客户信息包括：客户名称、销售、客户联系人、策划执行人、客户ID、客户类型
         */
      return hasRouteAuth('crm:orderList:medium') && !hasRouteAuth('crm:orderList:admin');
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'sealingStepsDetail') {
      to.meta.isSeal = true;
      to.meta.sealBillId = from.params.id;
      to.meta.active = from.params.stepId;
    } else {
      to.meta.isSeal = false;
    }
    next();
  },
  mounted() {
    this.batchModel = Number(this.$route.query.model) || 0; // 批量
    if (this.batchModel) {
      this.batchInfo = JSON.parse(localStorage.getItem('batchOrderInfo'));
      this.relatedInvoice.length = this.relatedContract.length = this.batchInfo.batchOrderInfo.length;
      this.formatBatchWrite(this.batchInfo);
    }

    this.orderId = Number(this.$route.params.orderId) || '';
    this.sealBillId = Number(this.$route.meta.sealBillId) || '';
    this.sealBillType = Number(this.$route.query.sealBillType) || null;
    this.active = Number(this.$route.meta.active) || '';

    this.title = '新增订单页';
    this.getInfo();
    this.orderOption = this.orderTypeList;
    window.removeReadOnly();
  },
  methods: {
    // order表单回填数据
    formatBatchWrite(obj) {
      const target = obj.batchOrderInfo;
      target.forEach(item => {
        const list = {
          platformId: item.platformId,
          orderPlatformOption: {
            id: item.platformId,
            value: item.platformName
          },
          resourceName: {
            value: item.name
          },
          resourceId: item.resourceId,
          resourceInfo: {
            // id: item.resourceId,
            value: item.name
          },
          accountId: item.accountId,
          articlesPrice: item.price,
          terminalType: obj.orderData.brandName,
          theme: obj.orderData.content
        };
        this.batchWrite.push(list);
      });
    },
    // 表单引用
    quoteForm() {
      this.$confirm('确认覆盖当前表单的所有信息？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon',
        center: true,
        type: 'warning'
      }).then(() => {
        const orderFormTarget = this.$refs[`orderForm${this.activeName}`][0];
        const orderFormQuote = this.$refs[`orderForm${this.quoteOrderInfo}`][0];
        const discountInfoTarget = this.$refs[`discountInfo${this.activeName}`][0];
        const discountInfoQuote = this.$refs[`discountInfo${this.quoteOrderInfo}`][0];
        const quoteOrder = this.objStringify(orderFormQuote.orderForm);
        // 账号下拉options
        const quoteResourceInfo = this.objStringify(orderFormQuote.resourceInfo);
        // 下单形式options
        const quoteFormList = this.objStringify(orderFormQuote.formList);
        // 价格选项无法引用
        const cacheArticlesPrice = orderFormTarget.orderForm.articlesPrice;
        quoteOrder.articlesPrice = null;
        quoteOrder.discountPrice = null;
        quoteOrder.taxAmount = null;
        orderFormTarget.resourceInfo = quoteResourceInfo;
        orderFormTarget.formList = quoteFormList;
        orderFormTarget.orderForm = quoteOrder;
        orderFormTarget.orderForm.articlesPrice = cacheArticlesPrice;
        discountInfoTarget.discountForm = this.objStringify(discountInfoQuote.discountForm);
      }).catch(() => {
        this.quoteOrderInfo = null;
      });
    },
    objStringify(obj) {
      return JSON.parse(JSON.stringify(obj));
    },
    handleClick(tab, event) {
      // console.log(tab, event);
      this.quoteOrderInfo = null;
    },
    removeTab(targetName) {
      const len = this.batchInfo.batchOrderInfo.length;
      this.$confirm(len > 1 ? '确认删除该新增订单' : '删除后将关闭本次新增订单', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        this.$message.closeAll();
        this.$message.success('删除成功');
        if (len <= 1) {
          this.$router.push({
            name: 'ConsultOrder'
          });
          localStorage.setItem('batchOrderInfo', null);
          return false;
        }
        // 删除单前活动页
        if (targetName === this.activeName) {
          if (this.activeName === '0') {
            this.activeName = '0';
          } else if (this.activeName === (len - 1).toString()) {
            this.activeName = (this.activeName * 1 - 1).toString();
          }
        } else {
          if (targetName * 1 + 1 === this.activeName * 1) {
            this.activeName = targetName;
          }
        }
        this.batchInfo.batchOrderInfo.splice(targetName * 1, 1);
        localStorage.setItem('batchOrderInfo', JSON.stringify(this.batchInfo));
        this.batchWrite.splice(targetName * 1, 1);
      }).catch(() => {

      });
    },
    // 获取当前登录人的信息 回填到销售输入框中
    getInfo() {
      const clientForm = this.$refs.clientForm;
      getInfo(0).then(({ data }) => {
        clientForm.clientForm.market = data.userName;
        clientForm.clientInfo.marketId = data.id;
      }, result => {
        // this.$message.error(result.message);
      }).catch(err => {
        console.error(err);
      });
    },
    orderFormVal(val) { // 获取输入框下单形式的数据
      if (val) this.orderFormValue = val;
    },

    paramObj(orderForm) { // 修改订单及资源信息传给接口的数据
      const standardData = JSON.parse(JSON.stringify(this.orderInfo));
      for (const i in standardData) {
        if (i === 'taxAmount') {
          if (orderForm[i] !== '') {
            standardData[i] = (orderForm[i] * 100).toFixed(0) - 0;
          } else if (orderForm[i] === 0) {
            standardData[i] = 0;
          }
        } else if (i === 'orderTime') {
          if (orderForm[i]) {
            const orderFormArr = ((orderForm[i] / 1000) + '').split('.');
            standardData[i] = orderFormArr[0];
          }
        } else if (i === 'articlesPrice') {
          if (orderForm[i] !== '') {
            standardData[i] = (Number(orderForm[i] * 100)).toFixed(0) - 0;
          } else if (orderForm[i] === 0) {
            standardData[i] = 0;
          }
        } else if (i === 'discountPrice') {
          standardData[i] = Number(orderForm[i]);
        } else if (i === 'platformId') {
          standardData[i] = orderForm.orderPlatformId;
        } else {
          standardData[i] = orderForm[i];
        }
      }
      return standardData;
    },
    numChange(costObj) { // 修改成本信息传给接口的数据
      const standardData = JSON.parse(JSON.stringify(this.discountInfo));
      for (const i in standardData) {
        if (i === 'douNum') {
          standardData[i] = (costObj[i] * 100).toFixed(0);
        } else {
          for (const j in standardData[i]) {
            if (!(j === 'channelId' || j === 'miniTeskId' || j === 'rebateCustomer' || j === 'rebateCustomerName')) {
              if (costObj[i][j] || costObj[i][j] === 0) {
                standardData[i][j] = (costObj[i][j] * 100).toFixed(0);
              }
            } else if (j === 'rebateCustomer') {
              // standardData[i][j] = costObj[i][j] ? costObj[i][j].id : '';
              standardData[i][j] = costObj[i][j] ? costObj[i][j] : '';
            } else {
              standardData[i][j] = costObj[i][j];
            }
          }
        }
      }
      return standardData;
    },

    toSubmit() {
      try {
        const clientForm = this.$refs.clientForm;
        const clientInfo = this.$refs.clientForm.clientInfo;
        const params = [];
        const promiseArr = [this.getFormPromise(clientForm.$refs.clientForm)];

        this.batchInfo.batchOrderInfo.forEach((item, index) => {
          const orderForm = this.$refs[`orderForm${index}`][0];
          const discountForm = this.$refs[`discountInfo${index}`][0];
          // console.log('ori', orderForm.orderForm);
          const obj = {
            clientInfo,
            orderInfo: this.paramObj(orderForm.orderForm),
            costBreakdown: this.numChange(discountForm.discountForm),
            contractIds: this.relatedContract[index] && this.relatedContract[index].ids ? this.relatedContract[index].ids.toString() : '',
            invoiceIds: this.relatedInvoice[index] && this.relatedInvoice[index].ids ? this.relatedInvoice[index].ids.toString() : ''
          };
          params.push(obj);
          promiseArr.push(orderForm.getFormPromise(index), discountForm.validateForm(true, index));
        });
        Promise.all(promiseArr).then(res => {
          const validateResult = res.every(item => !!item);
          if (validateResult) {
            this.requestFlag = true;
            params.forEach((item, index) => {
              if ((!item.costBreakdown.externalChannelObj.channelId && item.costBreakdown.externalChannelObj.costChannel !== '') ||
                (!item.costBreakdown.fansObj.channelId && item.costBreakdown.fansObj.fansTop !== '') ||
                (item.costBreakdown.starMapObj.rebateCustomer === '' && item.costBreakdown.starMapObj.starMapNum !== '') ||
                (!item.costBreakdown.talentObj.channelId && item.costBreakdown.talentObj.talentDividends !== '')) {
                this.$message.warning('请填写供应商/返点客户');
                this.activeName = index.toString();
                this.btnLoading = false;
                this.requestFlag = false;
                return;
              }
              // if (this.orderFormValue === '微任务直发' || this.orderFormValue === '微任务转发')
              // console.log('vali', item, item.orderInfo.platformId, item.orderInfo.orderFormId);
              if (item.orderInfo.platformId === 3 && (item.orderInfo.orderFormId === 3 || item.orderInfo.orderFormId === 4)) {
                if (!item.costBreakdown.miniTeskObj.miniTeskId) {
                  this.$message.warning('请填写微任务ID');
                  this.activeName = index.toString();
                  this.requestFlag = false;
                  return;
                } else {
                  // this.batchCreate(params);
                }
              } else {
                // this.batchCreate(params);
              }
            });
            if (this.requestFlag) this.batchCreate(params);
          } else {
            return false;
          }
        }).catch(error => {
          console.log(error);
          this.$message.warning('请检查信息是否填写完整');
          if (error === 'client') {
            // ..
          } else {
            this.activeName = error.toString();
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    async batchCreate(params) {
      try {
        this.btnLoading = true;
        const res = await createOrderBatch(params);
        if (res.code === 200 && res.data && res.data.length > 0) {
          let message = '';
          res.data.forEach((item, index) => {
            const target = this.batchInfo.batchOrderInfo[item.index];
            if (index > 0) {
              message += '<br>';
            }
            message += `${target.name} ${target.priceType} ${item.errMsg}，请修改后重新提交`;
          });
          this.$confirm(message, '', {
            confirmButtonText: '确定',
            showCancelButton: false,
            showClose: false,
            type: 'warning',
            center: true,
            iconClass: 'charge-icon',
            customClass: 'charge-message-box message-box',
            dangerouslyUseHTMLString: true
          }).then(() => {
            this.activeName = res.data[0].index.toString();
          });
        } else {
          this.$message.success('添加成功');
          this.$router.push({
            name: 'allOrder'
          });
          this.btnLoading = false;
          return;
        }
      } catch (error) {
        console.log(error);
      }
    },
    getFormPromise(form) {
      return new Promise((resolve, reject) => {
        form.validate(res => {
          if (res) {
            resolve(res);
          } else {
            reject('client');
          }
        });
      });
    },
    toBack() {
      this.$router.push({
        name: 'ConsultOrderDetail',
        params: {
          id: this.$route.query.consultId
        }
      });
    },
    // 关联相关
    getRelatedContract(value, index) {
      this.$set(this.relatedContract, index, value);
    },
    getRelatedInvoice(value, index) {
      this.$set(this.relatedInvoice, index, value);
    },
    deleteRelated(type, rowIndex, index) {
      if (type === 0) {
        this.relatedContract[index].options.splice(rowIndex, 1);
        this.relatedContract[index].ids.splice(rowIndex, 1);
      } else if (type === 1) {
        this.relatedInvoice[index].options.splice(rowIndex, 1);
        this.relatedInvoice[index].ids.splice(rowIndex, 1);
      }
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.create-order {
  .hiddent {
    height: 0;
    width: 0;
    margin: 0;
    visibility: hidden;
    overflow: hidden;
    padding: 0;
  }
  & ::v-deep {
    .el-input__inner  {
      width: 240px;
      line-height: 16px;
    }
    .el-form-item {
      margin-bottom: 32px;
    }
    .el-date-editor.el-input {
      width: 240px;
    }
  }
  .create-box {
    min-width: 1025px;
    background: #FBFBFD;
    padding: 32px 32px 62px;
    overflow-x: auto;
    .creat-client-oreder-box {
      display: flex;
      width: 100%;
    }
  }
}
.isMediumUser-style {
  margin-left: 0;
  width: 100%;
  & ::v-deep {
    .edit-order {
      width: 100% !important;
      .el-form-item {
        margin-left: 0 !important;
        margin-right: 5%;

      }
      .el-form-item:nth-of-type(2n) {
        margin-left: 0 !important;
      }
    }
  }
}

@media screen and (max-width: 1599px) {
  .creat-client-oreder-box {
    display: inline-block !important;
    .order-info {
      margin: 24px 0 0;
    }
  }
}
.batch-item {
  background:rgba(255,255,255,1);
  box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
  border-radius:12px;
  margin: 0 auto 24px;
  overflow: hidden;
  width: 100%;
  .order-info, .discount-info, .client-info {
    box-shadow: none;
  }
  & ::v-deep {
    .el-tabs--border-card {
      box-shadow: none;
      border: none;
      &>.el-tabs__content {
        padding: 0;
      }
    }
    .el-table::before {
      border: none;
      height: 0;
    }
    .el-select__tags {
      // overflow: hidden;
      // height: 100%;
      display: flex;
      align-items: center;
      max-width: 100%!important;
    }
    .el-tag.el-tag--info {
      color: #406EFF;
      background-color: #ecf1ff;
    }
    .el-tabs--border-card>.el-tabs__header {
      background: #fff;
      border-bottom: none;
      padding: 0 32px;
    }
    .el-tabs__item {
      border: 1px solid #DDDDDD;
      margin-right: 16px;
      border-radius: 4px;
      font-size:14px;
      font-weight:400;
      color:rgba(102,102,102,1);
      height: 30px;
      line-height: 30px;
    }
    .el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active {
      border-color: #406EFF;
      background:rgba(239,243,251,1);
      &.is-focus {
        box-shadow: none;
      }
    }
    .el-tabs__nav {
      padding: 1px;
    }
    .el-tabs__nav-prev, .el-tabs__nav-next {
      width: 24px;
      &:hover {
        color: #406EFF;
      }
    }
    .el-tabs__nav-next {
      right: -10px;
    }
  }
}
.quote-select {
  padding: 32px 32px 0;
  .el-form-item {
    margin-bottom: 0;
  }
}
.quote-tip {
  font-weight:400;
  color:rgba(153,153,153,1);
  line-height:14px;
  font-size: 14px;
  white-space: nowrap;
}
.table-btn {
  color: #406EFF;
  cursor: pointer;
}
.related-item {
  & ::v-deep {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
